<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">角色管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe="">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightByid(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightByid(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3,  in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightByid(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showSetRightVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
     <!-- 树形控件结构 -->
     <el-tree :data="rightsList" :props="trrProps"  show-checkbox
     node-key="id" default-expand-all :default-checked-keys="defkey" ref="treeRef" ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 添加角色的对话框 -->
    <el-dialog
  title="添加角色"
  :visible.sync="addRolesDialogVisible"
  width="50%"
  @close="removerRolecloed"
 >
  <el-form ref="addRoleRef" :model="addRolelist" label-width="80px">
  <el-form-item label="角色名称">
    <el-input v-model="addRolelist.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述">
    <el-input v-model="addRolelist.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addRolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addinfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //角色列表
      rolesList: [],
      //控制分配权限的对话框
      showSetRightVisible : false,
      //权限列表
      rightsList : [],
      //树形结构绑定数据
      trrProps : {
           label :'authName',
           children: 'children',
      },
      // 默认子节点的id值
      defkey : [],
      //即将分配权限的id
      roleid : '',
      //添加角色的开关
      addRolesDialogVisible : false,
      //添加角色
      addRolelist : {
        roleName : '',
        roleDesc : ''
      }
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //请求角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
      // console.log(res);
    },
    //根据id删除权限
    async removeRightByid(role, rightId) {
      const confirmRoult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmRoult !== "confirm") return this.$message.info("已取消");
      //发送请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      //重新渲染页面
      // this.getRolesList()
      role.children = res.data;
    },
    //分配权限
   async showSetRightDialog(role) {
     this.roleid =role.id
     //请求接口获取权限数据
   const {data:res} = await  this.$http.get('rights/tree')
   if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
   console.log(res);
   this.rightsList = res.data
    //将三级权限的id添加到数组
    this.getleafKeys(role,this.defkey)
    //打开对话框
      this.showSetRightVisible = true
    },
    //通过递归函数来将三级权限的id存到数组
    getleafKeys(node,arr) {
      if(!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getleafKeys(item,arr)
      })
    },
    //删除对话框的事件
    setRightDialogClosed() {
      this.defkey =[]
    },
    //分配角色权限
 async   allotRights() {
      //将点级的权限通过方法合并到数组并转换成字符串
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      console.log(idStr);
  const {data:res} = await this.$http.post(`roles/${this.roleid}/rights`,{rids : idStr})
     if(res.meta.status !==200) return this.$message.error(res.meta.msg)
     this.$message.success(res.meta.msg)
     //重新渲染页面
       this.getRolesList();
     //关闭对话框
     this.showSetRightVisible = false
    },
    //添加角色
  async  addinfo() {
  const {data:res} =await this.$http.post('roles',this.addRolelist)
  if(res.meta.status !==201) return this.$message.error(res.meta.msg)
  console.log(res);
   this.$message.success(res.meta.msg)
  //重新渲染页面
   this.getRolesList();
      this.addRolesDialogVisible = false  
    },
    //添加对话框关闭事件
    removerRolecloed() {
     this.addRolelist =  {
        roleName : '',
        roleDesc : ''
     }
    }
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>>

